import { requests } from './request';
import storage from './storage';
// 用户身份定义
export const USER_IDENTITIES = {
    USER: 0,           // 普通用户
    HEALTH_TEAM: 1,    // 健康管理团队
    ADMIN: 2           // 管理员
}

// 身份名称映射
export const IDENTITY_NAMES = {
    [USER_IDENTITIES.USER]: '用户',
    [USER_IDENTITIES.HEALTH_TEAM]: '健康团队',
    [USER_IDENTITIES.ADMIN]: '管理员'
}

// 身份验证：检查用户是否有权限设置指定身份
const validateIdentity = async (identity) => {
    try {
        // 获取用户信息
        const userInfo = await requests.getUserInfo();
        if (!userInfo) {
            console.error('用户信息不存在，无法验证身份');
            return false;
        }

        const userPrivilege = userInfo.privilege;

        // 根据用户权限验证身份设置权限
        switch (userPrivilege) {
            case 0: // 普通用户
                return identity === USER_IDENTITIES.USER;
            case 1: // 管理员
                return identity === USER_IDENTITIES.USER || identity === USER_IDENTITIES.HEALTH_TEAM;
            case 2: // 超级管理员
                return Object.values(USER_IDENTITIES).includes(identity);
            default:
                console.error('未知的用户权限级别:', userPrivilege);
                return false;
        }
    } catch (error) {
        console.error('身份验证失败:', error);
        return false;
    }
}

// 设置用户身份
const setIdentity = async (identity) => {
    try {
        // 验证身份设置权限
        const isValid = await validateIdentity(identity);
        if (!isValid) {
            console.error('无权限设置此身份');
            uni.showToast({
                title: '无权限设置此身份',
                icon: 'error'
            });
            return false;
        }

        // 存储身份到本地
        storage.setPermanent('user_identity', identity);
        console.log('身份设置成功:', IDENTITY_NAMES[identity]);

        uni.showToast({
            title: '身份设置成功',
            icon: 'success'
        });
        return true;
    } catch (error) {
        console.error('设置身份失败:', error);
        uni.showToast({
            title: '设置身份失败',
            icon: 'error'
        });
        return false;
    }
}

// 获取当前用户身份
const getIdentity = () => {
    try {
        const identity = storage.get('user_identity');
        // 如果没有设置身份，默认为普通用户
        if (identity === null || identity === undefined) {
            storage.setPermanent('user_identity', USER_IDENTITIES.USER);
            return USER_IDENTITIES.USER;
        }
        return identity;
    } catch (error) {
        console.error('获取身份失败:', error);
        return USER_IDENTITIES.USER;
    }
}

// 获取当前身份名称
const getIdentityName = () => {
    const identity = getIdentity();
    return IDENTITY_NAMES[identity] || IDENTITY_NAMES[USER_IDENTITIES.USER];
}

// 检查是否为指定身份
const isIdentity = (identity) => {
    return getIdentity() === identity;
}

// 检查是否为普通用户
const isUser = () => {
    return isIdentity(USER_IDENTITIES.USER);
}

// 检查是否为健康管理团队
const isHealthTeam = () => {
    return isIdentity(USER_IDENTITIES.HEALTH_TEAM);
}

// 检查是否为管理员
const isAdmin = () => {
    return isIdentity(USER_IDENTITIES.ADMIN);
}

// 重置身份为默认值（普通用户）
const resetIdentity = () => {
    try {
        storage.setPermanent('user_identity', USER_IDENTITIES.USER);
        console.log('身份已重置为普通用户');
        return true;
    } catch (error) {
        console.error('重置身份失败:', error);
        return false;
    }
}

// 获取所有可用的身份选项（基于当前用户权限）
const getAvailableIdentities = async () => {
    try {
        const userInfo = await requests.getUserInfo();
        if (!userInfo) {
            return [USER_IDENTITIES.USER];
        }

        const userPrivilege = userInfo.privilege;
        const availableIdentities = [];

        switch (userPrivilege) {
            case 0: // 普通用户
                availableIdentities.push(USER_IDENTITIES.USER);
                break;
            case 1: // 管理员
                availableIdentities.push(USER_IDENTITIES.USER, USER_IDENTITIES.HEALTH_TEAM);
                break;
            case 2: // 超级管理员
                availableIdentities.push(USER_IDENTITIES.USER, USER_IDENTITIES.HEALTH_TEAM, USER_IDENTITIES.ADMIN);
                break;
            default:
                availableIdentities.push(USER_IDENTITIES.USER);
        }

        return availableIdentities;
    } catch (error) {
        console.error('获取可用身份失败:', error);
        return [USER_IDENTITIES.USER];
    }
}

// 导出身份管理对象
export const identity = {
    // 常量
    USER_IDENTITIES,
    IDENTITY_NAMES,

    // 主要方法
    setIdentity,
    getIdentity,
    getIdentityName,

    // 身份检查方法
    isIdentity,
    isUser,
    isHealthTeam,
    isAdmin,

    // 工具方法
    resetIdentity,
    getAvailableIdentities,
    validateIdentity
}

export default identity;
